package service

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/google/uuid"
	"math/rand"
	"strconv"
	"time"
	"user_srv/basic/config"
	l "user_srv/basic/init"
	__ "user_srv/basic/proto"
	"user_srv/handler/models"
	"user_srv/pkg"
	"user_srv/until"
)

type Server struct {
	__.UnimplementedUserServer
}

// 发送验证码
func (s *Server) SendSms(_ context.Context, in *__.SendSmsReq) (*__.SendSmsResp, error) {
	count := config.Rdb.Get(config.Ctx, "sendSmsErr"+in.Mobile).Val()
	if count == "5" {
		return nil, fmt.Errorf("发送失败，请一分钟后再试")
	}

	sendsms := until.Sms{}
	code := rand.Intn(9000) + 1000
	err := sendsms.SendSms(in.Mobile, strconv.Itoa(code))
	if err != nil {
		return nil, fmt.Errorf("发送验证码失败")
	}
	config.Rdb.Set(config.Ctx, "sendSms"+in.Mobile, code, time.Minute)
	config.Rdb.Incr(config.Ctx, "sendSmsErr"+in.Mobile)
	config.Rdb.Expire(config.Ctx, "sendSmsErr"+in.Mobile, time.Minute)
	return &__.SendSmsResp{
		Message: "发送短信验证码成功",
	}, nil
}

// 注册
func (s *Server) Register(_ context.Context, in *__.RegisterReq) (*__.RegisterResp, error) {
	sms := config.Rdb.Get(config.Ctx, "sendSms"+in.Mobile).Val()
	var user models.User
	user.Mobile = in.Mobile
	user.Password = pkg.Md5(in.Password)
	err := user.GetUserByMobile()
	if err != nil {
		return nil, fmt.Errorf("获取用户信息失败")
	}
	if user.Id > 0 {
		return nil, fmt.Errorf("该用户已注册")
	}
	if sms != in.SmsCode {
		return nil, fmt.Errorf("验证码错误")
	}

	err = user.Register()
	if err != nil {
		return nil, fmt.Errorf("注册失败")
	}
	return &__.RegisterResp{
		UserId: int64(user.Id),
	}, nil
}

// 登录
func (s *Server) Login(_ context.Context, in *__.LoginReq) (*__.LoginResp, error) {
	sms := config.Rdb.Get(config.Ctx, "sendSms"+in.Mobile).Val()
	var user models.User
	user.Mobile = in.Mobile
	user.Password = pkg.Md5(in.Password)
	err := user.GetUserByMobile()
	if err != nil {
		return nil, fmt.Errorf("获取用户信息失败")
	}
	if user.Id == 0 {
		return nil, fmt.Errorf("该用户未注册，请前去注册")
	}
	if user.Password != pkg.Md5(in.Password) {
		return nil, fmt.Errorf("密码错误")
	}
	if sms != in.SmsCode {
		return nil, fmt.Errorf("验证码错误")
	}
	return &__.LoginResp{
		UserId: int64(user.Id),
	}, nil
}

// 添加预约
func (s *Server) AddReservation(_ context.Context, in *__.AddReservationReq) (*__.AddReservationResp, error) {
	house_num := rand.Intn(100)
	job_time, _ := time.Parse(time.DateTime, in.JobTime)
	reservation := models.Reservation{
		UserId:      uint(in.UserId),
		ServiceType: in.ServiceType,
		HouseNum:    uint(house_num),
		Address:     in.Address,
		JobTime:     job_time,
		CleanerId:   uint(in.CleanerId),
	}
	err := reservation.AddReservation()
	if err != nil {
		return nil, fmt.Errorf("预约失败")
	}
	l.SyncEs()
	return &__.AddReservationResp{
		ReservationId: int64(reservation.Id),
	}, nil
}

// 服务列表
func (s *Server) ReservationList(_ context.Context, in *__.ReservationListReq) (*__.ReservationListResp, error) {
	val := config.Rdb.Get(config.Ctx, "ReservationList").Val()

	var Reservation models.Reservation
	var ReserVationList []*__.ReservationList
	if val == "" {
		list, err := Reservation.ReservationList()
		if err != nil {
			return nil, fmt.Errorf("服务列表展示失败")
		}

		for _, r := range list {
			ReserVationList = append(ReserVationList, &__.ReservationList{
				ServiceType: r.ServiceType,
				HouseNum:    int64(r.HouseNum),
				CleanerId:   int64(r.CleanerId),
				Address:     r.Address,
			})
		}
		marshal, _ := json.Marshal(ReserVationList)
		config.Rdb.Set(config.Ctx, "ReservationList", marshal, time.Minute)
	}

	return &__.ReservationListResp{
		List: ReserVationList,
	}, nil
}

// 创建订单
func (s *Server) CreateOrder(_ context.Context, in *__.CreateOrderReq) (*__.CreateOrderResp, error) {
	var reservation models.Reservation
	err := reservation.GetReserVitionId(int(in.ReservationId))
	if err != nil {
		return nil, fmt.Errorf("获取预约信息失败")
	}
	if reservation.Id == 0 {
		return nil, fmt.Errorf("该预约不存在")
	}

	order := models.Order{
		UserId:         uint(in.UserId),
		ReservationId:  uint(in.ReservationId),
		OrderSn:        uuid.NewString(),
		ServiceAddress: reservation.Address,
		ServiceType:    reservation.ServiceType,
		OrderTotal:     reservation.EstimatePrice,
	}
	err = order.CreateOrder()
	if err != nil {
		return nil, fmt.Errorf("订单创建失败")
	}

	alipay := until.Pay{}
	return &__.CreateOrderResp{
		OrderId: int64(order.Id),
		Alipay:  alipay.Alipay(order.OrderSn, fmt.Sprintf("%.2f", order.OrderTotal)),
	}, nil
}

// 修改状态
func (s *Server) UpdateCleanerStatus(_ context.Context, in *__.UpdateCleanerStatusReq) (*__.UpdateCleanerStatusResp, error) {
	var cleaner models.Cleaner
	cleaner.Id = uint(in.Id)
	cleaner.CleanerStatus = uint(in.CleanerStatus)
	err := cleaner.UpdateStatus()
	if err != nil {
		return nil, fmt.Errorf("状态修改失败")
	}
	if cleaner.Id == 0 {
		return nil, fmt.Errorf("该保洁未存在")
	}
	return &__.UpdateCleanerStatusResp{
		Id: int64(cleaner.Id),
	}, nil
}

// 修改订单状态
func (s *Server) UpdateOrderStatus(_ context.Context, in *__.UpdateOrderStatusReq) (*__.UpdateOrderStatusResp, error) {
	var order models.Order
	order.Id = uint(in.Id)
	order.OrderStatus = uint(in.OrderStatus)
	err := order.UpdateOrderStatus()
	if err != nil {
		return nil, fmt.Errorf("创建订单失败")
	}
	if order.Id == 0 {
		return nil, fmt.Errorf("该订单不存在")
	}
	return &__.UpdateOrderStatusResp{
		Id: int64(order.Id),
	}, nil
}

// 我的订单
func (s *Server) OrderList(_ context.Context, in *__.OrderListReq) (*__.OrderListResp, error) {
	var order models.Order
	order.UserId = uint(in.MyOrderList)
	var MyList []*__.OrderList
	list, err := order.MyOrderList()
	if err != nil {
		return nil, fmt.Errorf("订单列表展示失败")
	}
	for _, o := range list {
		MyList = append(MyList, &__.OrderList{
			UserId:         int64(o.UserId),
			ReservationId:  int64(o.ReservationId),
			OrderSn:        o.OrderSn,
			ServiceType:    o.ServiceType,
			OrderTotal:     float32(o.OrderTotal),
			OrderStatus:    int64(o.OrderStatus),
			ServiceAddress: o.ServiceAddress,
		})
	}
	return &__.OrderListResp{
		List: MyList,
	}, nil
}

// 定时任务
